package com.tianxin.workbao.workBao.Activity;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.TransContract;
import com.tianxin.workbao.workBao.bean.TransPrice;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.TtransPriceProvide;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;
import com.tianxin.workbao.workBao.view.ExpandView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by hacker on 2017/6/22.
 */

public class TransPriceOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener {
    private ImageView arrowImageView;
    private FloatingActionButton saveFab;
    private TextView numberTv;
    private TextView splitLineTv;
    private TextView timeTv;
    private TextView sendCompanyTv;
    private TextView buyCompanyTv;
    private TextView coalNameTv;
    private ExpandView expandView;
    private TextView transPayInfo;
    private TextView transCompanyTv;
    private TextView sendAaaressTv;
    private TextView receiptAaaressTv;
    private Button deleteBtn;
    private Button oauthBtn;
    private Button finishBtn;
    private Button toVoidBtn;
    private Button changePriceBtn;

    private EditText inPriceET;
    private EditText outPriceET;
    private TextView startTimeET;
    private EditText lossValueET;
    private EditText lossPriceET;

    private TransContract mTransContract;
    private TransPrice mTransPrice;
    private TtransPriceProvide mTtransPriceProvide;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trans_price_option);
        super.initStatusBar(true);
        initData();

        initView();

        initEvent();

        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("新增运价");
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        saveFab = (FloatingActionButton) findViewById(R.id.save_fab);
        expandView = (ExpandView) findViewById(R.id.expandView);
        arrowImageView = (ImageView) findViewById(R.id.arrow);
        numberTv = (TextView) findViewById(R.id.number);
        splitLineTv = (TextView) findViewById(R.id.split_line);
        timeTv = (TextView) findViewById(R.id.time);
        sendCompanyTv = (TextView) findViewById(R.id.send_company);
        buyCompanyTv = (TextView) findViewById(R.id.buy_company);
        coalNameTv = (TextView) findViewById(R.id.coal_name);
        expandView = (ExpandView) findViewById(R.id.expandView);
        transPayInfo = (TextView) findViewById(R.id.trans_pay_info);
        transCompanyTv = (TextView) findViewById(R.id.trans_company);
        sendAaaressTv = (TextView) findViewById(R.id.send_address);
        receiptAaaressTv = (TextView) findViewById(R.id.receipt_address);
        deleteBtn = (Button) findViewById(R.id.delete_btn);
        oauthBtn = (Button) findViewById(R.id.oauth_btn);
        finishBtn = (Button) findViewById(R.id.finish_btn);
        toVoidBtn = (Button) findViewById(R.id.to_void_btn);
        changePriceBtn = (Button) findViewById(R.id.change_price_btn);

        deleteBtn.setVisibility(View.GONE);
        oauthBtn.setVisibility(View.GONE);
        finishBtn.setVisibility(View.GONE);
        toVoidBtn.setVisibility(View.GONE);
        changePriceBtn.setVisibility(View.GONE);
        splitLineTv.setVisibility(View.GONE);

        inPriceET = (EditText) findViewById(R.id.in_price);
        outPriceET = (EditText) findViewById(R.id.out_price);
        startTimeET = (TextView) findViewById(R.id.start_time);
        lossValueET = (EditText) findViewById(R.id.loss_value);
        lossPriceET = (EditText) findViewById(R.id.loss_price);

    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getExtras();
        mTransContract = (TransContract) bundle.getSerializable("contract");
        mTransPrice = new TransPrice();

        mTransPrice.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mTransPrice.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));
        mTransPrice.setTranscontractid((int) mTransContract.getId());
        mTransPrice.setTranscontractnum(mTransContract.getTctnum());
    }


    @Override
    public void initEvent() {
        //navigationIcon event
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TransPriceOptionActivity.this.finish();
            }
        });
        arrowImageView.setOnClickListener(this);
        saveFab.setOnClickListener(this);
        startTimeET.setOnClickListener(this);
    }

    @Override
    public void bindView() {
        numberTv.setText(mTransContract.getTctnum());
        sendCompanyTv.setText(mTransContract.getSendcompanyname());
        sendAaaressTv.setText(mTransContract.getSendaddress());
        buyCompanyTv.setText(mTransContract.getReceivecompanyname());
        receiptAaaressTv.setText(mTransContract.getReciveaddress());
        coalNameTv.setText(mTransContract.getCoaltypename());
        coalNameTv.setText(mTransContract.getCoaltypename());
        transCompanyTv.setText(mTransContract.getTranscompany());
        timeTv.setText(TimeUtils.parseDateTime(mTransContract.getTransstarttime()));
        transPayInfo.setText(mTransContract.getIsblurred() == 1 ? "区分内外价" : "不区分内外价");
    }

    @Override
    public void onBackPressed() {
        //alert
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.arrow:
                if (expandView.isExpand()) {
                    expandView.collapse();
                    arrowImageView.setImageResource(R.drawable.ic_arrow_drop_down_black_24dp);
                } else {
                    expandView.expand();
                    arrowImageView.setImageResource(R.drawable.ic_arrow_drop_up_black_24dp);
                }
                break;
            case R.id.save_fab:
                save();
                break;
            case R.id.start_time:
                getTimePickerDialog(new OnDateSetListener() {
                    @Override
                    public void onDateSet(com.jzxiang.pickerview.TimePickerDialog timePickerView, long millseconds) {
                        startTimeET.setText(TimeUtils.parseDateTime(new Date(millseconds)));
                    }
                }).show(getSupportFragmentManager(), "all");
                break;
        }
    }

    private void save() {
        if (mTransPrice == null) {
            showMessage("要保存的对像为空");
            return;
        }

        try {
            mTransPrice.setUnitprice(Float.valueOf(outPriceET.getText().toString()));
        } catch (NumberFormatException e) {
            showMessage("输入外部价格格式错误");
            e.printStackTrace();
            return;
        }
        if (mTransContract.getIsblurred() == 1) {
            try {
                mTransPrice.setIntransunitprice(Float.valueOf(inPriceET.getText().toString()));
            } catch (NumberFormatException e) {
                showMessage("输入内部价格格式错误");
                e.printStackTrace();
                return;
            }
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                mTransPrice.setStarttime(sdf.parse(startTimeET.getText().toString()));
            } catch (ParseException e) {
                showMessage("输入时间格式错误");
                e.printStackTrace();
                return;
            }

        } catch (NumberFormatException e) {
            showMessage("输入时间格式错误");
            e.printStackTrace();
            return;
        }
        if (mTransContract.getLosstype() != 1) {
            try {
                mTransPrice.setLossvalue(Float.valueOf(lossValueET.getText().toString()));
            } catch (NumberFormatException e) {
                showMessage("输入合理路耗错误");
                e.printStackTrace();
                return;
            }
            try {
                mTransPrice.setOutlossunitprice(Float.valueOf(lossPriceET.getText().toString()));
            } catch (NumberFormatException e) {
                showMessage("输入超损扣价错误");
                e.printStackTrace();
                return;
            }
        }
        mTransPrice.setAddtime(new Date());
        mTransPrice.setIsis(1);
        mTransPrice.setStatus(1);

        //save
        getTtransPriceProvide().save(mTransPrice);

    }

    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            getSweetAlertDialog(this).showSuccess("", "保存成功，将返回列表");
            this.finish();
        } else if (msg.contains("failure")) {
            Toast.makeText(this, "保存失败！\n " + msg.substring(msg.indexOf("failure") + 1, msg.length()), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 2000);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {

    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    public TtransPriceProvide getTtransPriceProvide() {
        if (mTtransPriceProvide == null) {
            mTtransPriceProvide = new TtransPriceProvide(this, this);
        }
        return mTtransPriceProvide;
    }

}
